package com.wqj.kyee.gps.bluetooth.server;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.wqj.kyee.gps.bluetooth.BtDevicesActivity;
import com.wqj.kyee.gps.nmea.NMEA;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.UUID;

public class ConnectionManager {

	private final String TAG = "ConnectionManager";
	
	private static ConnectionManager connectionManager;

	private BluetoothSocket bluetoothSocket;

	public final  String BT_UUID = "29913A2D-EB93-40cf-BBB8-DEEE26452197";

	private UUID uuid = UUID.fromString(BT_UUID);
	private BluetoothDevice btd =null;

	private Handler handler;

	private ConnectStateListener connectStateListener;

	private ReadCallBack readCallBack;

	private  ConnectionManager() {
	}
	
	public ConnectStateListener getConnectStateListener() {
		return connectStateListener;
	}

	public static ConnectionManager getInstance(){
		if(null == connectionManager){
			connectionManager = new ConnectionManager();
		}
		return connectionManager;
	}

	public void setConnectStateListener(ConnectStateListener connectStateListener) {
		this.connectStateListener = connectStateListener;
	}

	public Handler getHandler() {
		return handler;
	}

	public void setHandler(Handler handler) {
		this.handler = handler;
	}

	public BluetoothDevice getBtd() {
		return btd;
	}

	public void setReadCallBack(ReadCallBack readCallBack) {
		this.readCallBack = readCallBack;
	}

	public void init(BluetoothDevice bluetoothDevice){

		Log.d(TAG, "Start client connect thread");
		btd = bluetoothDevice;
		// Get a BluetoothSocket to connect with the given BluetoothDevice
		try {
			// MY_UUID is the app's UUID string, also used by the server code
			bluetoothSocket = btd.createRfcommSocketToServiceRecord(uuid);
		} catch (IOException e) {
		}
	}
	
	public  synchronized void connect(){
		BluetoothAdapter bluetoothAdapter =  BluetoothAdapter.getDefaultAdapter();
		bluetoothAdapter.cancelDiscovery();
		Log.d(TAG, "Start connect to bt-gps: " + bluetoothSocket);
		try {
			// Connect the device through the socket. This will block
			// until it succeeds or throws an exception
			bluetoothSocket.connect();
			if(null !=connectStateListener){
				connectStateListener.connectSuccess(btd);
			}
			if(null != handler){
				Message msg = Message.obtain();
				msg.what = BtDevicesActivity.BT_CLIENT_CONNECT_SUCCESS;
				msg.getData().putParcelable("btdevice",btd);
				handler.sendMessage(msg);
			}
			Log.d(TAG, "connect success");
		} catch (IOException connectException) {
			// Unable to connect; close the socket and get out
			Log.d(TAG, "failed: " + connectException.getMessage());
			if(null !=connectStateListener){
				connectStateListener.connectFail(btd);
			}
			Message msg = Message.obtain();
			msg.what = BtDevicesActivity.BT_CLIENT_CONNECT_FAIL;
			msg.getData().putParcelable("btdevice",btd);
			handler.sendMessage(msg);
			close();
		}
	}

	public boolean isConnected(){
		if(null != bluetoothSocket){
			return bluetoothSocket.isConnected();
		}
		return false;
	}

	private void close(){
		if(null != bluetoothSocket){
			try {
				bluetoothSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void cancel(){
		if(null != bluetoothSocket){
				close();
				Message msg = Message.obtain();
				msg.what = BtDevicesActivity.BT_SERVER_DISCONNECT_SUCCESS;
				msg.getData().putParcelable("btdevice",btd);
				handler.sendMessage(msg);
				if (null !=connectStateListener) {
					connectStateListener.disconnectSuccess(btd);
				}
		}
	}
	
	public void read(){
		Log.e("TAG","read--------------");
		try {
			InputStream inputStream = bluetoothSocket.getInputStream();
			InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
			BufferedReader bf = new BufferedReader(isr);
			String newLine = "";
			do {
				try {
					NMEA nmea = new NMEA();
					NMEA.GPSPosition gpsPosition = null;

					newLine = bf.readLine();
					gpsPosition = nmea.parse(newLine);
					if (null != gpsPosition && (gpsPosition.lat != 0.0) && (gpsPosition.lon!= 0.0)) {
						android.util.Log.e("TAG", gpsPosition.toString());
						if(null!=readCallBack){
							readCallBack.readInfo(gpsPosition);
						}
						Message msg = Message.obtain();
						msg.obj = gpsPosition;
						msg.what = BtDevicesActivity.GPS_BOARD_DATA;
//							mHandler.sendMessage(msg)
					}

				} catch (IOException e) {
					Log.e("TAG",e.getMessage()+"read--error------------");
					break;
				}

			} while (true);

		} catch (IOException e) {
			e.printStackTrace();
		}
//		isr = new InputStreamReader(`mmInStream`, "UTF-8")
	}

	public void parseLine(String line) {
		NMEA nmea = new NMEA();
		NMEA.GPSPosition gpsPosition = null;

		gpsPosition = nmea.parse(line);


		if (null != gpsPosition && (gpsPosition.lat != 0.0) && (gpsPosition.lon!= 0.0)) {
			android.util.Log.e(TAG, gpsPosition.toString());
			if( null != readCallBack){
				readCallBack.readInfo(gpsPosition);
			}
		}
	}

	public interface ConnectStateListener{
		void connectSuccess(BluetoothDevice bluetoothDevice);
		void disconnectSuccess(BluetoothDevice bluetoothDevice);
		void connectFail(BluetoothDevice bluetoothDevice);
	}

	public interface ReadCallBack{
		void readInfo(NMEA.GPSPosition gpsPosition);
	}

}
